package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
/**
 *
 * @Title: aipHSTCommission
 * @Description:华盛证券 将从中台系统提交的调佣申请任务，对应的 新佣金方案、新费用串号结果 实时回中台系统 --外部接口
 * @author: chieh
 * @date 2022-09-20 10:28:00
 *
 */

public class aipHSTCommission implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTCommission.class);
    String custapiid = getProperty.get("custapiid");
    String custapikey = getProperty.get("custapikey");
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def apiid = inObject.getString("apiid");
            if(custapiid!=apiid){

                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(apiid不匹配),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }
            def timestamp = inObject.getString("timestamp");
            def sign = inObject.getString("sign");
            def apitype = inObject.getString("apitype");
            log.debug("解析信息-" + "apiid: " + apiid + "timestamp: " + timestamp + "	sign: " + sign + "	apitype: " + apitype);

            //  String apikey = "c5e5e59567162a6be0533228d50a17e9";
            String signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + custapikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("sign加密MD5前：" + signfront);

            String signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            if (!signafter.equals(sign)) {
                log.error("处理失败(sign签名错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }
			//result 则按审核结果更新
			if(apitype=="result"){
				outData = resultData(eliteBean, inObject, dataSourceID);
			}else {// result 则按审核结果更新
				outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(apitype类型异常！)\",\"data\":[]}";
			}

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("开户(入金)客户信息完成返回结果:" + outData);

        return outData;
    }

   
	// 处理审核结果任务
    public static String resultData(EliteBean eliteBean, JSONObject inObject, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = dateformat.format(System.currentTimeMillis());

        // 生成批次号
        String batch_guid = KHUtil.getRandomString(36).toUpperCase();

        // 定义返回对象
        JSONObject resultJson = new JSONObject();

        try {

            JSONArray arrJsonArray = inObject.getJSONArray("data");
            int arrInt = arrJsonArray.size();
            log.debug("接入List数量:" + arrInt);

            String[] insertSQL = new String[arrInt*2];

            for (int i = 0; i < arrInt; i++) {

                JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);

				String taskId = KHUtil.FastJsonNull(arrSmsJson.getString("taskId"));//任务id（同申请调佣id）
				String customerId = KHUtil.FastJsonNull(arrSmsJson.getString("customerId"));//华盛号
                String status = KHUtil.FastJsonNull(arrSmsJson.getString("status"));//审核状态  1待处理，2已驳回，3已处理  沟通目前1 待处理无需同步
                String rejectcontent = KHUtil.FastJsonNull(arrSmsJson.getString("rejectcontent"));//驳回原因
                String chargeSerialNumberId = KHUtil.FastJsonNull(arrSmsJson.getString("chargeSerialNumberId"));//新费用串号ID
                String chargeSerialNumberName = KHUtil.FastJsonNull(arrSmsJson.getString("chargeSerialNumberName"));//新费用串号名称
                String finishTime = KHUtil.FastJsonNull(arrSmsJson.getString("finishTime"));//完成时间
                String approvalStatus = KHUtil.FastJsonNull(arrSmsJson.getString("approvalStatus"));//审核通过状态（20221212新增字段）1交易日生效 2立即生效

                String deal_result = KHUtil.isNullMSG("customerId", customerId) +KHUtil.isNullMSG("taskId", taskId) + KHUtil.isNullMSG("status",status)+ KHUtil.isNullMSG("chargeSerialNumberId",chargeSerialNumberId)+ KHUtil.isNullMSG("chargeSerialNumberName",chargeSerialNumberName)+ KHUtil.isNullMSG("finishTime",finishTime)+ KHUtil.isNullMSG("approvalStatus",approvalStatus) ;
                int deal_flag = KHUtil.isNull(deal_result) ? 0 : -1;
				
				if(rejectcontent==null){
					rejectcontent="";
				}

				//落库更新 
				insertSQL[i*2] = "update  hst_examine c  set c.auditStatus='" + status+ "',c.auditContent='" + rejectcontent+ "',c.chargeSerialNumberId='" + chargeSerialNumberId+ "',c.chargeSerialNumberName='" + chargeSerialNumberName+ "',c.finishTime='" + finishTime+ "',c.resultsynctime='" + createdate+ "',c.approvalStatus='" + approvalStatus+ "'  where c.hstid='"+customerId+"' and c.batchid='"+taskId+"' and typeid='005'";
				//详情表记录
                insertSQL[i*2+1] = "insert into hst_Commission(taskId,customerid,status,rejectcontent,chargeSerialNumberId,chargeSerialNumberName,finishTime,approvalStatus,createdate,deal_flag,deal_result) VALUES('"+taskId+"','"+customerId+"','"+status+"','"+rejectcontent+"','"+chargeSerialNumberId+"','"+chargeSerialNumberName+"','"+finishTime+"','"+approvalStatus+"',now(),'"+deal_flag+"','"+deal_result+"')";

            }

            // 处理批次信息
            String enddate = dateformat.format(System.currentTimeMillis());
            log.debug("提交数据库操作SQL集:" + insertSQL.toString());

            // 将数据插入数据库
            int[] sqlResult = eliteBean.updateBatch(insertSQL, dataSourceID);
            log.debug("提交数据库操作SQL结果:" + sqlResult.toString());
			
            // 生成处理完成时间
            endTime = System.currentTimeMillis();

            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", 4);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" +(endTime -startTime));

        }

        return resultJson.toString();
    }

}
